package com.iot.manager.ui.activities;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.material.button.MaterialButton;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.iot.manager.R;
import com.iot.manager.data.models.Device;
import com.iot.manager.network.ApiService;
import com.iot.manager.network.RetrofitClient;
import com.iot.manager.utils.DeviceWifiManager;
import com.iot.manager.utils.QRCodeUtils;
import com.iot.manager.utils.UdpManager;

import org.json.JSONException;
import org.json.JSONObject;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class DeviceProvisioningActivity extends AppCompatActivity {
    private static final int PERMISSION_REQUEST_CAMERA = 1;
    private static final int PERMISSION_REQUEST_STORAGE = 2;
    private static final int PICK_IMAGE = 3;
    private static final int SCAN_QR_REQUEST_CODE = 4;

    private ApiService apiService;
    private DeviceWifiManager wifiManager;
    private UdpManager udpManager;
    private TextView tvStatus;
    private ProgressBar progressBar;
    private MaterialButton btnScanQR;
    private MaterialButton btnLoadQR;
    private MaterialButton btnConnectWifi;
    private Device deviceInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_provisioning);

        setupToolbar();
        initViews();
        setupListeners();
    }

    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle(R.string.device_provisioning);
        }
    }

    private void initViews() {
        tvStatus = findViewById(R.id.tv_status);
        progressBar = findViewById(R.id.progress_bar);
        btnScanQR = findViewById(R.id.btn_scan_qr);
        btnLoadQR = findViewById(R.id.btn_load_qr);
        btnConnectWifi = findViewById(R.id.btn_connect_wifi);

        apiService = RetrofitClient.getInstance().getApiService();
        wifiManager = new DeviceWifiManager(this);
        udpManager = new UdpManager();
    }

    private void setupListeners() {
        btnScanQR.setOnClickListener(v -> checkCameraPermissionAndScan());
        btnLoadQR.setOnClickListener(v -> checkStoragePermissionAndPickImage());
        btnConnectWifi.setOnClickListener(v -> connectToWifi());
    }

    private void checkCameraPermissionAndScan() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    PERMISSION_REQUEST_CAMERA);
        } else {
            startQRScanner();
        }
    }

    private void checkStoragePermissionAndPickImage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13及以上使用READ_MEDIA_IMAGES权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_MEDIA_IMAGES},
                        PERMISSION_REQUEST_STORAGE);
            } else {
                openImagePicker();
            }
        } else {
            // Android 13以下使用READ_EXTERNAL_STORAGE权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        PERMISSION_REQUEST_STORAGE);
            } else {
                openImagePicker();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                         @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CAMERA) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startQRScanner();
            } else {
                Toast.makeText(this, R.string.camera_permission_required, Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == PERMISSION_REQUEST_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openImagePicker();
            } else {
                Toast.makeText(this, R.string.storage_permission_required, Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void startQRScanner() {
        // 强制竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
        Intent intent = new Intent(this, QRScannerActivity.class);
        intent.putExtra("title", getString(R.string.scan_qr_prompt));
        intent.putExtra("hint", getString(R.string.scan_qr_hint));
        startActivityForResult(intent, SCAN_QR_REQUEST_CODE);
    }

    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, PICK_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == SCAN_QR_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            String qrContent = data.getStringExtra("qr_content");
            if (qrContent != null) {
                handleQRCodeResult(qrContent);
            }
        } else if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            try {
                String qrContent = QRCodeUtils.decodeQRCodeFromImage(this, selectedImage);
                if (qrContent != null) {
                    handleQRCodeResult(qrContent);
                } else {
                    Toast.makeText(this, R.string.error_invalid_qr_code, Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                Toast.makeText(this, R.string.error_reading_qr_code, Toast.LENGTH_SHORT).show();
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
        
        // 恢复屏幕方向
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
    }

    private void handleQRCodeResult(String qrContent) {
        try {
            // 解析二维码内容
            // 格式: deviceId|deviceType|devicePassword|wifiSSID|wifiPassword
            String[] parts = qrContent.split("\\|");
            if (parts.length != 5) {
                throw new IllegalArgumentException("Invalid QR code format");
            }

            deviceInfo = new Device();
            deviceInfo.setDeviceId(parts[0]);
            deviceInfo.setType(parts[1]);
            deviceInfo.setPassword(parts[2]);

            // 跳转到配网页面
            DeviceNetworkConfigActivity.start(this, deviceInfo, parts[3], parts[4]);
            finish();
        } catch (Exception e) {
            Toast.makeText(this, R.string.error_invalid_qr_code, Toast.LENGTH_SHORT).show();
        }
    }

    private void registerDevice() {
        showProgress(true);
        updateStatus(getString(R.string.registering_device));

        apiService.registerDevice(deviceInfo).enqueue(new Callback<Device>() {
            @Override
            public void onResponse(Call<Device> call, Response<Device> response) {
                if (response.isSuccessful() && response.body() != null) {
                    deviceInfo = response.body();
                    updateStatus(getString(R.string.device_registered));
                    btnConnectWifi.setEnabled(true);
                } else {
                    updateStatus(getString(R.string.error_registering_device));
                }
                showProgress(false);
            }

            @Override
            public void onFailure(Call<Device> call, Throwable t) {
                updateStatus(getString(R.string.error_network));
                showProgress(false);
            }
        });
    }

    private void connectToWifi() {
        if (deviceInfo == null) {
            Toast.makeText(this, R.string.error_no_device_info, Toast.LENGTH_SHORT).show();
            return;
        }

        showProgress(true);
        updateStatus(getString(R.string.connecting_wifi));

        // 连接到设备热点
        wifiManager.connectToDeviceWifi(deviceInfo.getDeviceId(), deviceInfo.getPassword(), deviceInfo.getDeviceId(), 
            new DeviceWifiManager.ConnectionCallback() {
                @Override
                public void onSuccess() {
                    updateStatus(getString(R.string.connected_to_device));
                    btnConnectWifi.setEnabled(false);
                }

                @Override
                public void onError(String error) {
                    updateStatus(getString(R.string.error_connecting_device));
                    Toast.makeText(DeviceProvisioningActivity.this, error, Toast.LENGTH_SHORT).show();
                }
            });
    }

    private void sendWifiConfig() {
        // 获取当前连接的WiFi信息
        String currentWifiSSID = wifiManager.getCurrentWifiSSID();
        String currentWifiPassword = wifiManager.getCurrentWifiPassword();

        // 构建配置数据
        String configData = String.format("%s:%s:%s:%s",
                currentWifiSSID,
                currentWifiPassword,
                RetrofitClient.getInstance().getBaseUrl(),
                deviceInfo.getDeviceId());

        // 通过UDP发送配置
        udpManager.sendConfig(configData, new UdpManager.UdpCallback() {
            @Override
            public void onSuccess() {
                runOnUiThread(() -> {
                    updateStatus(getString(R.string.config_sent));
                    waitForDeviceConnection();
                });
            }

            @Override
            public void onError(String error) {
                runOnUiThread(() -> {
                    updateStatus(getString(R.string.error_sending_config));
                    Toast.makeText(DeviceProvisioningActivity.this, error, Toast.LENGTH_SHORT).show();
                    showProgress(false);
                });
            }
        });
    }

    private void waitForDeviceConnection() {
        // 等待设备连接服务器
        // 这里可以通过WebSocket监听设备状态变化
        // 当设备上线时，配网完成
        updateStatus(getString(R.string.waiting_device_connection));
    }

    private void showProgress(boolean show) {
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        btnScanQR.setEnabled(!show);
        btnLoadQR.setEnabled(!show);
        btnConnectWifi.setEnabled(!show);
    }

    private void updateStatus(String status) {
        tvStatus.setText(status);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (udpManager != null) {
            udpManager.close();
        }
    }
} 